from Queue import Queue, Empty, Full

class ConnectionPool(Queue):
    def __init__(self, constructor, poolsize=5):
        Queue.__init__(self, poolsize)
        self.constructor = constructor

    def get(self, block=1):
        try:
            return self.empty() and self.constructor() or Queue.get(self, block)
        except Empty:
            return self.constructor()

    def put(self, obj, block=1):
        try:
            return self.full() and None or Queue.put(self, obj, block)
        except Full:
            pass



class Constructor:
    def __init__(self, function, *args, **kwargs):
        self.f      = function
        self.args   = args
        self.kwargs = kwargs

    def __call__(self):
        return apply(self.f, self.args, self.kwargs)
